package simulation;

import brain.DrawMemory;
import java.util.Queue;
import view.Runner;
import view.View;
/**
 * @author  Owner
 */
@SuppressWarnings("unchecked")
public class VisualEngine implements Runnable {
    
    private Queue bigQueue;

    private Visualizer visualizer;

    private String sortType;
    
    private Integer[] temp;
    
    private boolean init = true;

    private boolean pause;

    private boolean skip;
    
    private boolean skipped;
    
    public VisualEngine(Integer[] temp, Queue bigQueue, Visualizer visualizer) {
	this.bigQueue = bigQueue;
	this.visualizer = visualizer;
	this.temp=temp;
    }

    public void run() {
	DrawMemory memory;
	try {
	    while (!bigQueue.isEmpty()) {
		if (!init && !skipped) {
		    Thread.sleep(1000);
		}
		Painter.getInstance().setWorkArray(temp);
		memory = (DrawMemory) bigQueue.poll();
		sortType = memory.getSortType();
//		System.out.println("________________" + sortType+ "________________");
			View.getInstance().setSimulationName(sortType);

		while (!memory.isEmpty()) {
		    synchronized (this) {
			if(pause){
			    wait();
			}
			if(skip){
			    skip = false;
			    skipped = true;
			    visualizer.skipSimulation();
			    break;
			}else{
			    skipped = false;
			}
		    }
					if (!sortType.equals("Merge Sort")) {
						visualizer.visualSwap(memory.popDrawCommand());
					} else {
						Painter.getInstance().setMergeArray(memory.popDrawCommand().getMergeArray());
						Thread.sleep(Mover.getSpeed() * 100);
					}
		}
		init = false;
	    }
	} catch (InterruptedException e) {
	    System.err.println("Exception in Swap Memory");
	}
	
	Runner.getInstance().setSimMode(false);
    }

    public synchronized void pause() {
	visualizer.pauseSimulation();
	pause = true;
    }
    
    public synchronized void resume() {
	visualizer.resumeSimulation();
	pause = false;
	notify();
    }
    
    public synchronized void skip() {
	skip = true;
    }
}
